package com.sgb.auction.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import com.sgb.auction.R;
import com.sgb.auction.databinding.AuctionHallFragmentBinding;
import com.sgb.auction.entity.AuctionListEntity;
import com.sgb.auction.adapter.AuctionHallAdapter;
import com.sgb.auction.entity.RequestBean;
import com.sgb.auction.viewmodule.AuctionHallFragmentModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.XRecyclerView;
import java.util.List;

/**
 * Time:2021/11/19
 * AUTHOR:F_Q
 * Description:拍卖大厅tab
 */
public class AuctionHallFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener{
    private static String KEY_TYPE = "key_type";
    private static String NO = "no";
    private RequestBean requestBean = new RequestBean();
    private AuctionHallFragmentBinding mBinding;
    private AuctionHallFragmentModel mModel;
    private AuctionHallAdapter auctionhalladapter;
    private boolean isLoadMore = false;
    private SuperSwipeRefreshLayout swipeRefreshMainRecruitmentFragment;
    private String type = "";
    private String SearcheName = "";//搜索内容
    public boolean isInIt = false; //是否初始化完成
    private String longitudes;//经度
    private String latitudes;//纬度
    private String sort = "";
    //地区筛选项实现
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private String province = "";
    private String city = "";

    public static AuctionHallFragment newInstance(String type, String no) {
        AuctionHallFragment fragment = new AuctionHallFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putString(NO, no);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.auction_hall_fragment, container, false);
        mModel = new ViewModelProvider(this).get(AuctionHallFragmentModel.class);
        mModel.setActivity(AuctionHallFragment.this);
        longitudes = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        latitudes = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        if (TextUtils.isEmpty(longitudes)) {
            longitudes = "0";
        }
        if (TextUtils.isEmpty(latitudes)) {
            latitudes = "0";
        }
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        super.initView();
        if (auctionhalladapter == null) {
            auctionhalladapter = new AuctionHallAdapter(getActivity(), R.layout.auction_hall_items, null);
        }
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mBinding.recyclerView.setAdapter(auctionhalladapter);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initDataList();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                requestBean.page++;
                //上拉加载更多
                mModel.AuctionHallList(requestBean);
            }
        });
        auctionhalladapter.setOnItemClick(new AdapterOnItemClick<AuctionListEntity>() {
            @Override
            public void onItemClick(AuctionListEntity auctionListEntity, int position) {
                mModel.getWebView(auctionListEntity.getNo());
            }
        });
        isInIt = true;
        viewData();
    }
    private void viewData() {
        //初始化popview
        initializePopView();
    }

    private void initializePopView() {
        //地区
        initAddressPopup();
        //综合排序
        mBinding.sortmethod.initPopup(mBinding.grayLayout, mBinding.popLine, this);
    }

    private void initDataList() {
        isLoadMore = false;
        requestBean.page = 1;
        if (TextUtils.equals((String) getArguments().get(KEY_TYPE), "2")){
            requestBean.setState(TextUtils.isEmpty((String) getArguments().get(NO))?"":(String) getArguments().get(NO));
            requestBean.setLocalLat(latitudes);
            requestBean.setLocalLng(longitudes);
        }
        requestBean.setKeyword(SearcheName);
        mModel.AuctionHallList(requestBean);
    }

    @Override
    protected void onLazyLoad() {
        //type = 1不展示筛选项    type =2展示筛选项
        if (TextUtils.equals((String) getArguments().get(KEY_TYPE), "1")) {
            mBinding.llScreeningItems.setVisibility(View.GONE);
            initDataList();
        } else {
            mBinding.llScreeningItems.setVisibility(View.VISIBLE);
        }
        mModel.getSortType(this, TextUtils.isEmpty((String) getArguments().get(NO))?"":(String) getArguments().get(NO));
    }

    /**
     * 列表数据信息
     *
     * @param data
     * @param isLastPage
     */
    public void setAuctionHallList(List<AuctionListEntity> data, boolean isLastPage) {
        RecyclerRefreshing();
        if (isLoadMore) {
            if (data != null && data.size() > 0) {
                auctionhalladapter.addDatas(data);
            }
            mBinding.recyclerView.setNoMore(isLastPage);
        } else {
            if (data != null && data.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                auctionhalladapter.setDatas(data);
                mBinding.recyclerView.scrollToPosition(0);
                mBinding.recyclerView.setNoMore(isLastPage);
            } else {
                auctionhalladapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setVisibility(View.GONE);
            }
        }
    }


    private void RecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void onPullRefresh(SuperSwipeRefreshLayout swipeRefreshMainRecruitmentFragment) {
        this.swipeRefreshMainRecruitmentFragment = swipeRefreshMainRecruitmentFragment;
        swipeRefreshMainRecruitmentFragment.setLoadMore(false);
        initDataList();
    }

    public void setSearchName(String searcheName) {
        if (!TextUtils.isEmpty(searcheName)) {
            SearcheName = searcheName;
        } else {
            SearcheName = "";
        }
        initDataList();
    }

    //地区
    private void initAddressPopup() {
        mBinding.district.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null || scrData.size() == 0) {
                    mModel.getAddressModel(AuctionHallFragment.this);
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                    mBinding.district.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                province = "";
                city = "";
                requestBean.setProvince(province);
                requestBean.setCity(city);
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    province = entity.getProvinceNo();
                    requestBean.setProvince(province);
                    mBinding.district.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        city = entity.getCityNo();
                        requestBean.setCity(city);
                        mBinding.district.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                initDataList();
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(1, null);
            } else {
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
            }
        });
    }

    //pop初始化数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "综合排序":
                mModel.getSortType(this, TextUtils.isEmpty((String) getArguments().get(NO))?"":(String) getArguments().get(NO));
                break;
        }
    }

    //pop点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "综合排序":
                if (!TextUtils.equals(no, sort)) {
                    sort = no;
                    requestBean.setSortMethod(sort);
                }
                break;
        }
        //刷新数据
        initDataList();
    }

    public void setSortTypeList(List<CommonPopEntity> datas) {
        setChooseItemData(1, datas);
    }

    //弹窗信息
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case 1://排序方式
                mBinding.sortmethod.setData(data, sort);
                break;
        }
    }

    /**
     * 地址信息
     * @param data
     */
    public void setAddressList(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(data, true);
           /* String ProvinceCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE, "");
            if (!TextUtils.isEmpty(ProvinceCode)) {
                mAddressPop.setData(data, true, ProvinceCode);
            } else {
                mAddressPop.setData(data, true);
            }*/
            mBinding.popLine.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(-2, null);
            } else {
                mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
            }
            mAddressPop.showPopwindow0(mBinding.popLine);
        }
    }
}
